﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Nest;

namespace EsDemo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var node = new Uri("http://localhost:9200");
            var settings = new ConnectionSettings(node);
            var client = new ElasticClient(settings);

            //创建索引
            var resp = client.Indices.Create("test", opt =>
            {
                return opt.Map<ESTest>(m => m.AutoMap());
            });
            Console.WriteLine("创建索引结果:" + resp.Acknowledged);
            Console.WriteLine(resp.DebugInformation);


            var model = new ESTest()
            {
                Name = "青城1",
                Age = 20,
                Info = "顺其自然，不代表我们可以不努力，而是努力之后有勇气接受成败。",
                Id = 2,
                CreateTime = DateTime.Now
            };

            var indexResp = client.Index(model, i => i.Index("test"));
            if (indexResp.IsValid)
            {

            }

            var res = client.Search<ESTest>(a => a.Index("test")
           .Query(a =>
               a.Match(m =>
                   m.Field(f => f.Info).Query("顺其自然"))));
            foreach (var item in res.Documents)
            {
                Console.WriteLine(item.Name + " " + item.Info);
            }

            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
    [ElasticsearchType(RelationName = "estest")]
    public class ESTest
    {
        [Number(NumberType.Integer, Name = "id")]
        public int Id { get; set; }

        [Text(Name = "name")]
        public string Name { get; set; }

        [Number(NumberType.Integer, Name = "age")]
        public int Age { get; set; }

        [Text(Name = "info", Analyzer = "ik_smart")]
        public string Info { get; set; }

        [Date(Name = "createtime", Format = "yyyy-MM-dd||yyyy-MM-dd HH:mm:ss")]
        public DateTime CreateTime { get; set; }
    }
}
